#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <string.h>
#include <assert.h>

#define BUFSIZE 512

char content[] = "<html><head><title>NETWORK</title></head>"
    "<body><font size=+5><br> error occurs! please check file name again!"
    "</font></body></html>";

void send_error(int sockfd) {
    char protocol[] = "HTTP/1.0 400 Bad Request\r\n";
    char server[] = "Server:Linux Web Server \r\n";
    char content_len[] = "Content-length:2048\r\n";
    char content_type[] = "Content-type:text/html\r\n\r\n";
    write(sockfd, protocol, strlen(protocol));
    write(sockfd, server, strlen(server));
    write(sockfd, content_len, strlen(content_len));
    write(sockfd, content_type, strlen(content_type));
    write(sockfd, content, strlen(content));
}

void send_data(FILE *fp, int sockfd) {
    char protocol[] = "HTTP/1.0 200 OK\r\n";
    char server[] = "Server: Linux web server\r\n";
    char content_len[] = "Content-length:2048\r\n";
    char content_type[] = "Content-type:text/html\r\n\r\n";
    write(sockfd, protocol, strlen(protocol));
    write(sockfd, server, strlen(server));
    write(sockfd, content_len, strlen(content_len));
    write(sockfd, content_type, strlen(content_type));
    char buf[BUFSIZE] = {0};
    while (fgets(buf, BUFSIZE, fp) != NULL) 
        write(sockfd, buf, strlen(buf));
    fclose(fp);
}

void * handle_request(void *arg) {
    int connfd = *(int *)arg;
    char buf[BUFSIZE] = {0};
    int rc = read(connfd, buf, BUFSIZE);
    // 非http
    if (strstr(buf, "HTTP/") == NULL) {
        send_error(connfd);
        close(connfd);
    }
    // http
    printf("buf = %s\n", buf);
    char *p;
    p = strtok(buf, " /");
    printf("method = %s\n", p);
    p = strtok(NULL, " /");
    printf("file = %s\n", p);
    FILE* fp = fopen(p, "r");
    if (fp == NULL) {
        send_error(connfd);
    } else {
        send_data(fp, connfd);
    }
    close(connfd);
    return NULL;
}

int main(int argc, char **argv) {
    if (argc != 2) {
        printf("[Usage] :%s <port>\n", argv[0]);
        return 0;
    }
    int server_fd = socket(PF_INET, SOCK_STREAM, 0);
    assert(server_fd != -1);
    
    struct sockaddr_in addr, client_addr;
    addr.sin_port = htons(atoi(argv[1]));
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_family = AF_INET;

    int rc = bind(server_fd, (struct sockaddr *)&addr, sizeof addr);
    assert(rc != -1);

    listen(server_fd, 20);
    while (1) {
        int len = sizeof(client_addr);
        int connfd = accept(server_fd, (struct sockaddr *)&client_addr, &len);
        
        pthread_t pid;
        pthread_create(&pid, NULL, handle_request, (void *)&connfd);
        pthread_detach(pid);
    }
    close(server_fd);
    return 0;
}
